<template>
  <div>
    <Row class="list_row" style="margin-top: 0px;;min-height: 400px;">
      <Row style="margin: 5px 0px 10px 0px;">

        <Input v-model="searchKeyword" :placeholder="$t('common.teamSePlaceTips')" style="width: 200px;margin-right: 20px"/>
        <Button  class="btnWhite" type="primary" icon="ios-search" style="margin-right: 20px" @click="search">{{$t('search')}}</Button>
        <!-- 此处权限修改为：训练中心无权限，仅超级管理员可新增、修改、删除 -->
        <Button  class="btnWhite" type="primary" icon="md-add" @click="showAddModal" v-if="roleId == '1'">{{$t('teamP.addTeam')}}</Button>
      </Row>
      <Table :columns="deviceColumn" border :data="dataList" stripe :no-data-text="noDataMsg">
        <template slot-scope="{ row, index }" slot="seq">
          {{(currentPage - 1) * pageSize + index + 1}}
        </template>
        <template slot-scope="{ row, index }" slot="status">
          <span v-if="row.onlineStatus == 1" style="color:#2d8cf0">{{ this.$t('common.online')}}</span>
          <span v-else>{{ this.$t('common.outline')}}</span>
        </template>
      </Table>
      <div class="div_page">
        <Page :total="totalCount" :current="currentPage" :page-size="pageSize"
              show-total show-elevator prev-text="<" next-text=">" @on-change="pageChg"/>
      </div>
    </Row>

    <!-- 新增运动队弹窗 -->
    <Modal v-model="entityModelVisiable" :mask-closable="false" width="800" :title="entityModelTitle" mask>
      <Form ref="entityFormRef" :model="entityForm" :rules="addFormRules" :label-width="120">
        <FormItem :label="$t('common.teamName')"  prop="name">
          <Input v-model="entityForm.name" :placeholder="$t('common.teamSePlaceTips')"></Input>
        </FormItem>  
        <FormItem :label="$t('common.traninerCenter')" prop="trainCenterId" v-if="isCanChooseTc && entityForm.opeType == 'add'">
          <Select v-model="entityForm.trainCenterId" filterable :placeholder="$t('common.trainSePlaceTips')" @on-change="changeTrain" >
            <Option v-for="tc in trainCenterList" :value="tc.id" :key="tc.id">{{tc.name}}</Option>
          </Select>
        </FormItem>
        <FormItem :label="$t('common.traninerCenter')" prop="trainCenterName" v-else >
          <Input v-model="entityForm.trainCenterName" placeholder="" readonly="readonly"></Input>
        </FormItem>
      </Form>
      <div class="flex justify-center" >
        <Transfer ref="myTransfer" style="margin: 0px 10px" :data="peopleList" :titles="[this.$t('teamP.peopleList'), this.$t('teamP.assignedP')]" filterable
          :filter-method="searchCoach" :target-keys="selCoachIds" :render-format="transferRender" :list-style="listStyle"
          @on-change="transferOnChange"></Transfer>
      </div>
      <div slot="footer" style="text-align: center">
        <Button @click="entityModelVisiable=false">{{$t('cancel')}}</Button>
        <Button type="primary" @click="saveOrUpdate" :loading="saveLoading" style="margin-left: 15px">
          <span v-if="!saveLoading">{{$t('save')}}</span>
          <span v-else>{{$t('save')}}....</span>
        </Button>
      </div>
    </Modal>
  <!-- 查看学员列表 -->
  <Modal
      v-model="peopleVisiable"
      :mask-closable="false"
      width="800"
      :title="$t('common.previewBtn')"
      
    >
    <div slot="footer"></div>
    
      <Table
        :columns="peopleColumn"
        border
        :data="peopleListTable"
        stripe
        style="min-height: 278px"
      >
       
      </Table>
      
    </Modal>
  </div>
</template>
<script>
import TrainCenterApi from '@/api/trainCenterApi'
import TrainerApi from '@/api/trainerApi'
import TeamApi from '@/api/teamApi'
import { isEmpty, copyObj } from '@/libs/util'
import AnalysisReportApi from '@/api/analysisReportApi'
import { mapActions } from 'vuex'
export default {
  data () {
    return {
      clickTrainCenterId: '',
      peopleList:[],
      peopleListTable:[],
      selCoachIds: [],
      roleId: '',
      saveLoading: false,
      searchKeyword: '',
      noDataMsg:  this.$t('common.noData'),
      entityModelTitle: this.$t('teamP.addTeam'),
      isCanChooseTc: false,
      selTrainCenterId: '',
      trainCenterList: [],
      entityModelVisiable: false,
      peopleVisiable:false,
      listStyle:{
       width:'250px'
      },
      entityForm: {
        id: '',
        name: '',
        sn: '',
        trainCenterId: ''
      },
      addFormRules: {
        trainCenterId: [
          { required: true, message: this.$t('common.trainMustTips'), trigger: 'blur' }
        ],
        name: [
          { required: true, message:  this.$t('common.nameMustTips'), trigger: 'blur' },
          { type: 'string', max: 32, message: this.$t('common.namelenLow32Tips'),trigger: 'blur' }
        ],
        sn: [
          { required: true, message: this.$t('common.snMustTips'), trigger: 'blur' },
          { type: 'string', max: 64, message: this.$t('common.namelenLow64Tips'),  trigger: 'blur' }
        ]
      },
      showDeviceLoading: false,
      totalCount: 20,
      currentPage: 1,
      pageSize: 10,
      dataList: [],
      peopleColumn:[ {
        title: this.$t('common.seq'), 
          slot: "seq",
          width: '110',
          render: (h, params) => {
            return h('span', params.index + 1)
          }
        },
        {
          title: this.$t('common.avatar'), 
          width:'80',
          key: 'avator',
          render: (h, params) => {
            // return h('strong', params.row.avatar)
            if (!params.row.avatar) {
             
             return h("div", {
                   class: "avatorBox",
                 },
           )
           }
            return h("img", {
              style: {
                // 样式
                width: "20px",
                border: "1px solid",
              },
              attrs: {
                src: params.row.avatar,
              },})}
        },

        {
          title: this.$t('teamP.teamMember'), 
          key: 'nickName'
        },
        {
          title: this.$t('trainerP.peopleLevel'), 
          key: 'level',
          render: (h, params) => {
            let levelCn=''
            if(params.row.level==="1"){
              levelCn=this.$t('trainerP.primary')
            }else if(params.row.level==="2"){
              levelCn=this.$t('trainerP.intermediate')
            }else if(params.row.level==="3"){
              levelCn=this.$t('trainerP.senior')
            }
            return h('span', levelCn)
          }
        },
        {
          title: this.$t('common.traninerCenter'),  
          key: 'trainCenterName'
        },
      ],
      deviceColumn: [
        {
          title: this.$t('common.seq'), 
          slot: "seq",
          width: '110',
          render: (h, params) => {
            return h('span', {
              class: 'sortBlock'
            }, params.index + 1)
          }
        },
        {
          title:  this.$t('common.teamName'), 
          key: 'name'
        },

        {
          title: this.$t('common.traninerCenter'), 
          key: 'trainCenterName'
        },
        {
          title:  this.$t('common.createTime'),  
          key: 'createTime'
        },
        {
          title: this.$t('common.optColumn'), 
          key: 'action',
          width: 210,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'warning',
                  size: 'small'
                },
                class: "btnBlue",
                style: {
                  marginRight: '15px',
                  display: (this.roleId == '1') ? 'inline' : 'none'
                },
                on: {
                  click: () => {
                    this.showEditModal(params.row)
                  }
                }
              }, this.$t('common.editBtn')),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  marginRight: '15px',
                },
                class: 'btnYellow',
                on: {
                  click: () => {
                    this.showPeopleDialog(params.row.id)
                  }
                }
              }, this.$t('common.previewBtn')),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  display: (this.roleId == '1') ? 'inline' : 'none'
                },
                class: 'btnRed',
                on: {
                  click: () => {
                    this.del(params.row)
                  }
                }
              },  this.$t('common.deleteBtn'))
            ])
          }
        }],

      selDeviceId: '',
      sportsModalTitle: '',
      sportsRecordDataArr: [],
      sportsRecordTotalCount: 0,
      sportsRecordCurrentPage: 1,
      sportsRecordCountPageSize: 10,
      sportsRecordModelVisiable: false,
      startQueryDate: '',
      endQueryDate: '',
      startQueryDateVal: '',
      endQueryDateVal: '',
      sportsRecordColumn: [
        {
          title: this.$t('common.seq'), 
          slot: "seq",
          width: '110',
        },
        {
          title: this.$t('common.trainerName'), 
          key: 'trainerName'
        },
        {
          title: this.$t('common.planName'), 
          key: 'planName'
        },
        {
          title: this.$t('common.courseName'), 
          key: 'courseName'
        },
        {
          
          title: this.$t('common.sportStartColumn'), 
          key: 'startTrainTime'
        },
        {
          title: this.$t('common.sportEndColumn'), 
          key: 'endTrainTime'
        },
        {
          title: this.$t('common.optColumn'), 
          key: 'action',
          width: 180,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'info',
                  size: 'small'
                },
                style: {
                  marginRight: '15px'
                },
                on: {
                  click: () => {
                    this.playVideo(params.row)
                  }
                }
              }, this.$t('common.videoView')  ),
              h('Button', {
                props: {
                  type: 'info',
                  size: 'small'
                },
                style: {
                  marginRight: '15px'
                },
                on: {
                  click: () => {
                    this.viewAnalysis(params.row)
                  }
                }
              }, this.$t('common.analysisBtn') )
            ])
          }
        }
      ]
    }
  },
  watch: {
    'clickTrainCenterId': function (val) {
   
      this.initCoachList()
    },
  },
  created () {
    this.initFunc()
  },
  mounted () {
    this.getUserInfo().then(res => {
      this.roleId = res.roleId
    })
  },
  methods: {
    ...mapActions([
      'getUserInfo'
    ]),
    showPeopleDialog(id){
      this.peopleVisiable = true;
      this.fetchPeopleDataList(id);
     
    },
    fetchPeopleDataList(id){

TeamApi.getSportsPeople(id).then(res => {
        const data = res.data.data.pageResult

        this.peopleListTable = data
console.log("gggggggggggg",data)
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    changeTrain(v){
      this.clickTrainCenterId =this.entityForm.trainCenterId
  
    },
    initFunc () {
      TrainCenterApi.userTrainCenterScope().then(res => {
        const data = res.data.data
        
        if (data.canSelect == '1') {
          this.isCanChooseTc = true
        
          this.trainCenterList = []
          if (data.list.length > 0) {
            for (var i = 0; i < data.list.length; i++) {
              var tc = data.list[i]
              this.trainCenterList.push(tc)
            }
          }
       
          this.selTrainCenterId = ''
        } else {
          
          this.selTrainCenterId = data.trainCenterId
        }
        this.search()
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    initCoachList () {
      var param = { 'pageSize': 999, 'currentPage': 1, 'trainCenterId': this.clickTrainCenterId }
      TrainerApi.pageResult(param).then(res => {
        const data = res.data.data.pageResult.items

        for (var i = 0; i < data.length; i++) {
          var coach = data[i]
          coach['key'] = coach.id
        }
        this.peopleList = data
        console.log("edit",data)
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    search () {
      this.currentPage = 1
      this.fetchDataList()
    },
    fetchDataList () {
      this.noDataMsg = this.$t('common.loading')
      this.dataList = []
      var param = { 'pageSize': this.pageSize, 'currentPage': this.currentPage }
      if (this.selTrainCenterId.length > 0) {
        param.trainCenterId = this.selTrainCenterId
      }
      if (this.searchKeyword.length > 0) {
        param.name = this.searchKeyword
      }
      TeamApi.pageResult(param).then(res => {
        this.dataList = res.data.data.pageResult.items
        this.totalCount = res.data.data.pageResult.totalCount
        this.noDataMsg = this.$t('common.noData')
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    showAddModal () {
      this.$refs.entityFormRef.resetFields()
      this.entityForm = {
        id: '',
        name: '',
        sn: '',
        trainCenterId: ''
      }
      this.peopleList = []
      // 不可选的，直接设置trainCenterId
      if (!this.isCanChooseTc) {
        this.entityForm.trainCenterId = this.selTrainCenterId
      }
      this.entityForm.opeType = 'add'
      this.entityModelTitle = this.$t('teamP.addTeam')
      this.entityModelVisiable = true
    },
    showEditModal (row) {

      TeamApi.get(row.id).then(res => {
        this.clickTrainCenterId = row.trainCenterId
        
      this.selCoachIds = row.userIds;
        this.entityForm.opeType = 'edit'
        this.$refs.entityFormRef.resetFields()
        this.entityModelVisiable = true
        this.entityModelTitle = this.$t('teamP.editTeam')
        this.entityForm = copyObj(row)
        
      })
    },
    saveOrUpdate () {
    
      this.$refs.entityFormRef.validate((valid) => {
        if (valid) {
          this.saveLoading = true
          // if (this.entityForm.id == '') {
          //   this.entityForm.trainCenterId = this.selTrainCenterId
          // }

          const postData = {
            ...this.entityForm,
            userIds: this.selCoachIds
          }

          const doPost = this.entityForm.id ? TeamApi.update(postData) : TeamApi.save(postData)
          doPost.then(response => {
            this.saveLoading = false
            if (this.entityForm.id == '') {
              this.$Message.success(this.$t('common.addSuc'))
            } else {
              this.$Message.success(this.$t('common.editSuc'))
            }
            this.$refs.entityFormRef.resetFields()
            this.entityModelVisiable = false
            this.fetchDataList()
          }, error => {
            this.saveLoading = false
            this.$Message.error(error.response.data.msg)
          })
        }
      })
    },
    pageChg (selPage) {
      this.currentPage = selPage
      this.fetchDataList()
    },
    del (row) {
      this.$Modal.confirm({
        title:this.$t('common.dDeleteTitleConfirm'),
        content:  this.$t('common.DdeleteCt'),
        okText: this.$t('common.deleteBtn'),
        cancelText: this.$t('cancel'),
        onOk: () => {
          this.doDel(row.id)
        }
      })
    },
    doDel (id) {
      TeamApi.delete(id).then(res => {
        this.$Message.success(this.$t('common.deleteSuc'))
        this.fetchDataList()
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    // 重置查询
    reset (isOpen) {
      this.sportsRecordModelVisiable = isOpen,
      this.sportsRecordDataArr = []
      this.startQueryDate = ''
      this.startQueryDateVal = ''
      this.endQueryDate = ''
      this.endQueryDateVal = ''
      if (isOpen) {
        this.searchSportsRecords()
      }
    },
    showSportsRecordModal (id, name) {
      this.sportsModalTitle =this.$t('teamP.recordP') + name
      this.selDeviceId = id
      this.sportsRecordModelVisiable = true
      this.sportsRecordCurrentPage = 1
      this.searchSportsRecords()
    },
    searchSportsRecords () {
      this.sportsRecordDataArr = []
      var param = {
        'currentPage': this.sportsRecordCurrentPage,
        'pageSize': this.sportsRecordCountPageSize,
        'deviceId': this.selDeviceId
      }
      if (this.startQueryDateVal.length > 0) {
        param.startQueryDate = this.startQueryDateVal
      }
      if (this.endQueryDateVal.length > 0) {
        param.endQueryDate = this.endQueryDateVal
      }
      AnalysisReportApi.querySportsRecordPageResult(param).then(res => {
        this.sportsRecordDataArr = res.data.data.items
        this.sportsRecordTotalCount = res.data.data.totalCount
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    sportsRecordPageChg (selPage) {
      this.sportsRecordCurrentPage = selPage
      this.searchSportsRecords()
    },
    startDateChange (formatTime) {
      this.startQueryDateVal = formatTime
    },
    endDateChange (formatTime) {
      this.endQueryDateVal = formatTime
    },
    playVideo (row) {
      const routeData = this.$router.resolve({
        name: 'video',
        query: { sportsRecordId: row.id }
      })
      window.open(routeData.href, '_blank')
    },
    viewAnalysis (row) {
      const routeData = this.$router.resolve({
        name: 'groupReport',
        query: { id: row.id }
      })
      window.open(routeData.href, '_blank')
    },
    startDateChange (formatTime) {
      this.startQueryDateVal = formatTime
    },
    endDateChange (formatTime) {
      this.endQueryDateVal = formatTime
    },
    transferRender (coach) {
      if(!coach.avatar){
        if(this.$i18n.locale === 'zh-CN'){
          return `<div class="tranBox"><div class="avatorBox"></div> ${coach.nickName}  ( ${coach.phone} )</div>`
        }else{
          return `<div class="tranBox"><div class="avatorBox"></div> ${coach.nickName}  ( ${coach.mail} )</div>`
        }
      
      }else{
        if(this.$i18n.locale === 'zh-CN'){
          return `<div class="tranBox"> <img src="${coach.avatar}" style="width:20px;height:20px;" /> ${coach.nickName}  ( ${coach.phone} )</div>`
        }else{
          return `<div class="tranBox"> <img src="${coach.avatar}" style="width:20px;height:20px;" /> ${coach.nickName}  ( ${coach.mail} )</div>`
        }
      }
      
    },
    transferOnChange (newTargetKeys, direction, moveKeys) {
      this.selCoachIds = newTargetKeys
    },
    searchCoach (data, query) {
      // console.log("data:" + JSON.stringify(data))
      if(this.$i18n.locale === 'zh-CN'){
        return data.nickName.indexOf(query) > -1 || data.phone.indexOf(query) > -1
      }else{
        return data.nickName.indexOf(query) > -1 || data.mail.indexOf(query) > -1
      }
    
    }
  }
}
</script>
<style lang="less">

.avatorBox{
  background:url('../../assets/images/icon_tx_boy.png') no-repeat;
  background-size:contain;
  width:20px;
  height:20px;
  margin:5px;
  margin-left:0;
}
.tranBox{
  font-size:12px;
  display:flex;
  align-items:center;
}
.ivu-transfer-list-content-item{
  display:flex;
  
}
.avatorBox{
  background:url('../../assets/images/icon_tx_boy.png');
  background-size:contain;
  width:20px;
  height:20px;
  margin:5px;
  margin-left:0
}
</style>
